package cn.wp.common.core.plugin.email;

import cn.hutool.core.collection.CollectionUtil;
import cn.wp.common.core.WpVar;
import cn.wp.common.core.exception.WpException;
import cn.wp.common.core.model.WpState;
import cn.wp.common.core.plugin.template.SimpleSpringTemplateEngine;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.thymeleaf.context.Context;
import org.thymeleaf.dialect.IDialect;
import org.thymeleaf.spring5.SpringTemplateEngine;
import org.thymeleaf.spring5.dialect.SpringStandardDialect;
import org.thymeleaf.templatemode.TemplateMode;
import org.thymeleaf.templateresolver.StringTemplateResolver;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.validation.constraints.NotNull;
import java.io.File;
import java.util.Map;

/**
 * 
 * 邮件发送接口实现
 * 
 * @author chenyb
 *
 */
@Service
public class MailService {
	
	/**
	 * 注入MailSender
	 */
	@Autowired
    private JavaMailSender mailSender;

	@Autowired
	SimpleSpringTemplateEngine simpleSpringTemplateEngine;
	
	/**
	 * 读取配置文件中的发送用户信息
	 */
	@Value("${spring.mail.username}")
    private String fromEmail;

	/**
	 * Text方式表达式 Today is: [(${today})]
	 * https://cloud.tencent.com/developer/article/1475358
	 *
	 * @param textTemplate
	 * @param values
	 * @return
	 */
	public String mailTextBuilder(String textTemplate, Map<String, Object> values) {
		return mailBodyBuilder(textTemplate,values,TemplateMode.TEXT);
	}

	public String mailHtmlBuilder(String htmlTemplate, Map<String, Object> values) {
		return mailBodyBuilder(htmlTemplate,values,TemplateMode.HTML);
	}

	private String mailBodyBuilder(String template, Map<String, Object> values,TemplateMode templateMode) {
		Context ctx = new Context();
		ctx.setVariables(values);
		return simpleSpringTemplateEngine.process(template,ctx);
	}

	/**
	 * 文本类型邮件发送业务实现
	 */
	public WpState sendSimple(
			@NotNull String[] toEmail,
			@NotNull String subject, 
			@NotNull String body
			) {
		WpState mailSenderModal = new WpState();
		try {
			SimpleMailMessage message = new SimpleMailMessage();
	        message.setFrom(fromEmail);
	        
	        /**
	         * 收件人邮件地址
	         */
	        message.setTo(toEmail);
	        message.setSubject(subject);
			// 添加抄送，解决发送邮件被识别成垃圾邮件
			message.setCc(fromEmail);
	        message.setText(body);
	        mailSender.send(message);
		}catch(MailException e) {
			mailSenderModal.setCode(WpVar.NO_FOR_INT);
			mailSenderModal.setMessage(e.getMessage());
			throw new WpException("文本邮件发送出错",e);
		}
		return mailSenderModal;
	}

	public WpState sendMime(@NotNull String toEmail, @NotNull String subject, @NotNull String mailBody) {
		return this.sendMime(new String[]{toEmail},subject,mailBody,null,false);
	}

	public WpState sendMime(@NotNull String[] toEmail, @NotNull String subject, @NotNull String mailBody) {
		return this.sendMime(toEmail,subject,mailBody,null,false);
	}

	/**
	 * Mime类型邮件发送业务实现
	 */
	public WpState sendMime(
			@NotNull String[] toEmail,
			@NotNull String subject, 
			@NotNull String mailBody,
			Map<String, String> files,
			boolean isAttachment) {
		WpState mailSenderModal = new WpState();
		try {
			MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(fromEmail);
            helper.setTo(toEmail);
			// 添加抄送，解决发送邮件被识别成垃圾邮件
			helper.setCc(fromEmail);

			helper.setSubject(subject);
            helper.setText(mailBody, true);
            
            /**
             * 判断附件是否为空
             */
            if(!StringUtils.isEmpty(files)){
            	/**
            	 * 多附件处理
            	 */
				files.entrySet().forEach(entry->{
                    try {
	            		FileSystemResource file = new FileSystemResource(new File(entry.getValue()));
	            		
	            		if(isAttachment) {
	            			helper.addAttachment(entry.getKey(), file);
	            		}else {
							helper.addInline(entry.getKey(),file);
	            		}
					} catch (MessagingException e) {
						mailSenderModal.setCode(WpVar.NO_FOR_INT);
						mailSenderModal.setMessage(e.getMessage());
						throw new WpException("Mime类型邮件发送出错",e);
					}
            	});
            }
            
	        mailSender.send(message);
		} catch (MessagingException e) {
			mailSenderModal.setCode(WpVar.NO_FOR_INT);
			mailSenderModal.setMessage(e.getMessage());
			throw new WpException("Mime类型邮件发送出错",e);
		}catch(MailException e) {
			mailSenderModal.setCode(WpVar.NO_FOR_INT);
			mailSenderModal.setMessage(e.getMessage());
			throw new WpException("Mime类型邮件发送出错",e);
		}
		return mailSenderModal;
	}

	public static void main(String[] args) {
		MailService mailService = new MailService();
		Map<String,Object> data = CollectionUtil.newHashMap();
		data.put("today","2019-09-09");
		String body = mailService.mailHtmlBuilder("<p>Today is: <span th:text=\"${today}\">13 february 2011</span>.</p>",data);
		String text = mailService.mailTextBuilder("Today is: [(${today})]",data);
		//String body2 = mailService.mailBodyBuilder("Today is: ${today}",data);

		System.err.println(body);
		System.err.println(text);
	}
	
}